package com.daka.tools.wechatPay;

import com.daka.tools.ConfigUtil;
import com.daka.tools.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class WechatPaymentUtil {

    private static Logger LOGGER = LoggerFactory.getLogger(WechatPaymentUtil.class);

    public static String generateMchPayJsRequestJson(String prepay_id, String appId, String key) {
        String package_ = "prepay_id=" + prepay_id;
        PayJsRequest payJsRequest = new PayJsRequest();
        payJsRequest.setAppId(appId);
        payJsRequest.setNonceStr(UUID.randomUUID().toString().trim().replaceAll("-", ""));
        payJsRequest.setPackage_(package_);
        payJsRequest.setSignType("MD5");
        payJsRequest.setTimeStamp(System.currentTimeMillis() / 1000 + "");
        Map<String, String> mapS = MapUtil.objectToMap(payJsRequest);
        String paySign = SignatureUtil.generateSign(mapS, key);
        PayJsWithAppId jsObj = new PayJsWithAppId();
        jsObj.setNonceStr(payJsRequest.getNonceStr());
        jsObj.setPackage_(package_);
        jsObj.setSignType("MD5");
        jsObj.setTimeStamp(payJsRequest.getTimeStamp());
        jsObj.setPaySign(paySign);
        String json = JsonUtil.toJSONString(jsObj);
        return json.replaceAll("timeStamp", "timestamp");
    }

    public static PayJsWithAppId generateMchPayJsRequestObject(String prepay_id, String appId, String key) {
        String package_ = "prepay_id=" + prepay_id;
        PayJsRequest payJsRequest = new PayJsRequest();
        payJsRequest.setAppId(appId);
        payJsRequest.setNonceStr(UUID.randomUUID().toString().trim().replaceAll("-", ""));
        payJsRequest.setPackage_(package_);
        payJsRequest.setSignType("MD5");
        payJsRequest.setTimeStamp(System.currentTimeMillis() / 1000 + "");
        Map<String, String> mapS = MapUtil.objectToMap(payJsRequest);
        String paySign = SignatureUtil.generateSign(mapS, key);
        PayJsWithAppId jsObj = new PayJsWithAppId();
        jsObj.setNonceStr(payJsRequest.getNonceStr());
        jsObj.setPackage_(package_);
        jsObj.setSignType("MD5");
        jsObj.setTimeStamp(payJsRequest.getTimeStamp());
        jsObj.setPaySign(paySign);
//        String json = JsonUtil.toJSONString(jsObj);
//        return json.replaceAll("timeStamp", "timestamp");
        return jsObj;
    }

    public static UnifiedOrderResult getUnifiedorderResult(String commodityDes, String batchCode, int total,
                                                           String remoteIp, String openId) {
        UnifiedOrder unifiedOrder = new UnifiedOrder();

        unifiedOrder.setAppid(ConfigUtil.getWxAppId());
        unifiedOrder.setMch_id(ConfigUtil.getMchId());
        unifiedOrder.setNonce_str(UUID.randomUUID().toString().trim().replaceAll("-", ""));
        unifiedOrder.setBody(commodityDes);
        // unifiedorder.setOut_trade_no(batchCode );
        unifiedOrder.setOut_trade_no(batchCode + DateUtil.date2Str(new Date(), "HHmmss"));
        unifiedOrder.setTotal_fee(String.valueOf(total));
        unifiedOrder.setSpbill_create_ip(remoteIp);// IP
//        unifiedorder.setNotify_url(ConfigUtil.getNotifyUrl());  回调URL
        unifiedOrder.setNotify_url(ConfigUtil.getAppRoot() + "/order/success");
        unifiedOrder.setTrade_type("JSAPI");// JSAPI，NATIVE，APP，WAP

        unifiedOrder.setOpenid(openId);

//        return PayMchAPI.payUnifiedorder(unifiedorder, ConfigUtil.getApiKey());
        return PayMchAPI.payUnifiedorder(unifiedOrder, ConfigUtil.getApiKey());
    }

    public static RefundResult getRefundResult(String batchCode, String transactionId, int total, String appid,
                                               String mchid, String apiKey, String cert) {
        LOGGER.info("enter getRefundResult:batchCode={},transactionId={},total={}", batchCode, transactionId, total);
        Refund refund = new Refund();
        refund.setAppid(appid);
        refund.setMch_id(mchid);
        refund.setNonce_str(UUID.randomUUID().toString().trim().replaceAll("-", ""));
        refund.setTransaction_id(transactionId);
        refund.setOut_trade_no("");
        refund.setOut_refund_no(batchCode + DateUtil.date2Str(new Date(), "MMddHHmmss"));
        refund.setTotal_fee(String.valueOf(total));
        refund.setRefund_fee(String.valueOf(total));
        refund.setOp_user_id(mchid);
        LOGGER.info("exit getRefundResult Refund:{}", refund);
        return PayMchAPI.payRefund(refund, apiKey, cert, mchid);
    }

    public static RefundQueryResult getRefundQueryResult(String transactionId, String appid, String mchid,
                                                         String apiKey) {
        RefundQuery refund = new RefundQuery();
        refund.setAppid(appid);
        refund.setMch_id(mchid);
        refund.setNonce_str(UUID.randomUUID().toString().trim().replaceAll("-", ""));
        refund.setTransaction_id(transactionId);
        refund.setOut_trade_no("");
        refund.setOut_refund_no("");
        refund.setRefund_id("");
        return PayMchAPI.payRefundQuery(refund, apiKey);
    }

    public static PayQueryResult getPayOrderResult(String transaction_id, String batchCode) {

        PayOrderQuery payOrderQuery = new PayOrderQuery();

        payOrderQuery.setAppid(ConfigUtil.getWxAppId());
        payOrderQuery.setMch_id(ConfigUtil.getMchId());
        payOrderQuery.setNonce_str(UUID.randomUUID().toString().trim().replaceAll("-", ""));
        if (transaction_id == null || "".equals(transaction_id)) {
            payOrderQuery.setOut_trade_no(batchCode);
        } else {
            payOrderQuery.setTransaction_id(transaction_id);
        }

//        return PayMchAPI.payOrderQueryResult(payOrderQuery, ConfigUtil.getApiKey());
        return PayMchAPI.payOrderQueryResult(payOrderQuery, ConfigUtil.getApiKey());
    }
}